package com.wecheir.controller;

import com.wecheir.entity.Farm;
import com.wecheir.entity.FarmData;
import com.wecheir.entity.FarmDataT;
import com.wecheir.service.FarmService;
import com.wecheir.service.UserService;
import com.wecheir.utils.DateUtil;
import com.wecheir.utils.ResponseUtils;
import com.wecheir.utils.UploadUtil;
import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.PageData;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 农田管理controller层
 */
@Controller
@RequestMapping("/app/farm")
public class FarmController {
    @Resource
    FarmService farmService;
    @Resource
    UserService userService;
    @GetMapping(value = "list")
    public String list(){return "admin/farm/list";}
//    @RequiresPermissions("farm:list")
//    @PostMapping("list")
//    @ResponseBody
//    public PageData<Farm> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
//                               @RequestParam(value = "limit",defaultValue = "10")Integer limit,
//                               ServletRequest request){}
     @GetMapping("add")
     public String add(){
    return "admin/farm/list";
}
//    @RequiresPermissions("farm:user:add")
/**
   保存新增农田数据
 */
    @PostMapping("/add")
    @ResponseBody
    public ResponseUtils add(@RequestBody Farm farm){
        farm.setCreateId(farm.getCreateId());
        farm.setUserId(farm.getUserId());
        farm.setCreateDate(new Date());
//          farmService.addFarm(farm);
        if(StringUtils.isBlank(farm.getName())){
            return ResponseUtils.setFailure("农田名称不能为空");
        }
        if(StringUtils.isBlank(farm.getSize())){
            return ResponseUtils.setFailure("农田面积不能为空");
        }
        if(StringUtils.isBlank(farm.getLocation())){
            return ResponseUtils.setFailure("农田地点不能为空");
        }
        if(StringUtils.isBlank(farm.getTemperature())){
            return ResponseUtils.setFailure("农田标准温度不能为空");
        }
        if(StringUtils.isBlank(farm.getHumidity())){
            return ResponseUtils.setFailure("农田相对湿度不能为空");
        }
        if(StringUtils.isBlank(farm.getIllumination())){
            return ResponseUtils.setFailure("农田光照强度不能为空");
        }

        if(farmService.getFarmNameCount(farm.getName())>0){
            return ResponseUtils.setFailure("农田名称已存在");
        }
        farmService.saveFarm(farm);
        return ResponseUtils.setSuccess("操作成功");
    }
    @GetMapping("edit")
    public String edit(String id, ModelMap modelMap){
        Farm farm = farmService.getFarmById(Integer.parseInt(id));
        modelMap.put("farm",farm);
        return "admin/farm/edit";
    }
    @PostMapping("/save")
    @ResponseBody
    public ResponseUtils save(String id,String location,String size,String remarks){

        return ResponseUtils.setSuccess("保存成功");
    }
    /**
     保存编辑农田数据
     */
//    @RequiresPermissions("farm:user:edit")
//    @PostMapping("edit")
//    @ResponseBody
//    public ResponseUtils edit(@RequestBody Farm farm, String id){
//        if(StringUtils.isBlank(id)){
//            return ResponseUtils.setFailure("农田ID不能为空");
//        }else{
//            farm.setId(Integer.parseInt(id));
//        }
//        if(StringUtils.isBlank(farm.getName())){
//            return ResponseUtils.setFailure("农田名称不能为空");
//        }
//        if(StringUtils.isBlank(farm.getSize())){
//            return ResponseUtils.setFailure("农田面积不能为空");
//        }
//        if(StringUtils.isBlank(farm.getLocation())){
//            return ResponseUtils.setFailure("农田位置不能为空");
//        }
//        if(StringUtils.isBlank(farm.getTemperature())){
//            return ResponseUtils.setFailure("农田标准温度不能为空");
//        }
//        if(StringUtils.isBlank(farm.getHumidity())){
//            return ResponseUtils.setFailure("农田相对湿度不能为空");
//        }
//        if(StringUtils.isBlank(farm.getIllumination())){
//            return ResponseUtils.setFailure("农田光照强度不能为空");
//        }
//        Farm oldFarm = farmService.getFarmById(farm.getId());
//        if(!oldFarm.getName().equals(farm.getName())){
//            if(farmService.getFarmNameCount(farm.getName())>0){
//                return ResponseUtils.setFailure("农田名称已存在");
//            }
//        }
//        farmService.updateFarm(farm);
//        return ResponseUtils.setSuccess("操作成功");
//    }

    @PostMapping("edit")
    @ResponseBody
    public ResponseUtils edit(Farm farm){
        if(StringUtils.isBlank(farm.getName())){
            return ResponseUtils.setFailure("农田名称不能为空");
        }
        if(StringUtils.isBlank(farm.getSize())){
            return ResponseUtils.setFailure("农田面积不能为空");
        }
        if(StringUtils.isBlank(farm.getLocation())){
            return ResponseUtils.setFailure("农田位置不能为空");
        }
        if(StringUtils.isBlank(farm.getTemperature())){
            return ResponseUtils.setFailure("农田标准温度不能为空");
        }
        if(StringUtils.isBlank(farm.getHumidity())){
            return ResponseUtils.setFailure("农田相对湿度不能为空");
        }
        if(StringUtils.isBlank(farm.getIllumination())){
            return ResponseUtils.setFailure("农田光照强度不能为空");
        }
        Farm oldFarm = farmService.getFarmById(farm.getId());
        if(!oldFarm.getName().equals(farm.getName())){
            if(farmService.getFarmNameCount(farm.getName())>0){
                return ResponseUtils.setFailure("农田名称已存在");
            }
        }
        farmService.updateFarm(farm);
        return ResponseUtils.setSuccess("操作成功");
    }

    /**
     删除农田数据
     */
//    @RequiresPermissions("farm:user:delete")
    @PostMapping("delete")
    @ResponseBody
    public ResponseUtils delete(@RequestParam(value = "id",required = false)String id){
        if(StringUtils.isBlank(id)){
            return ResponseUtils.setFailure("农田ID不能为空");
        }
//        Farm farm = farmService.getFarmById(Integer.parseInt(id));

        farmService.deleteFarm(Integer.parseInt(id));
        return ResponseUtils.setSuccess("操作成功");
    }

//    /** 多选删除农田数据
//     */
//    @RequiresPermissions("farm:user:delete")
//    @PostMapping("deleteSome")
//    @ResponseBody
//
//    public ResponseUtils deleteSome(@RequestBody List<Farm> farms){
//        if(farms == null || farms.size()==0){
//            return ResponseUtils.setFailure("请选择需要删除的农田");
//        }
//        for (Farm r : farms){
//            farmService.deleteFarm(r);
//        }
//        return ResponseUtils.setSuccess("操作成功");
//    }



    @GetMapping("/getAllFarmsById")
    @ResponseBody
    public ResponseUtils getAllFarmsById(String id,int page,int limit){

        return ResponseUtils.setSuccess("保存成功");
    }


    /**
     * 查询指定农田主的所有农田
     * @param id
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/getAllFarmsByUser")
    @ResponseBody
    public ResponseUtils getAllFarmsByUser(String id,int page,int limit){
        System.out.println("id==>"+id);
        System.out.println("page==>"+page);
        System.out.println("limit==>"+limit);
        List<Farm> list = farmService.getFarmByUser(id,page*limit,limit);
        return ResponseUtils.setSuccess(list);
    }


    /**
     * 查询指定农田的（温、湿度）数据情况
     * @return
     */
    @GetMapping("/FarmData")
    @ResponseBody
    public ResponseUtils FarmData(String farmId,  Date beginDate,  Date endDate){
        ResponseUtils responseUtils =new ResponseUtils();
        Map<String, Object> map = new HashMap<>();
        List<String> result = new ArrayList<String>();
        List<String> listTime = new ArrayList<>();
        List<FarmData> list = farmService.getFarmData(farmId,beginDate,endDate);
        result=DateUtil.getBetweenDates(DateUtil.getStringDate(beginDate),DateUtil.getStringDate(endDate));
        String[] temperArray ;
        String[] humidiArray;
        String[] illumiArray;

         if(list.size()>0){
//             String[] dateTimeArray =  (String[])list.toArray(new String[list.size()]);
             temperArray = new String[list.size()];
             humidiArray=new String[list.size()];
             illumiArray=new String[list.size()];
//             for (int i = 0; i < list.size(); i++) {
//                 listTime.add(DateUtil.getStringDate(list.get(i).getTime()));
//             }
//             Collections.sort(listTime);
//             Collections.sort(result);
//             for(int i = 0;i<=result.size()-listTime.size();i++){
//                 listTime.add(null);
//             }
             for (int i = 0; i < list.size(); i++) {

//                 if( listTime.get(i).isEmpty()!=false||listTime.get(i).compareTo(result.get(i)) !=0 ){
                     temperArray[i] = list.get(i).getTemperature();
                     humidiArray[i]=list.get(i).getHumidity();
                     illumiArray[i]=list.get(i).getIllumination();
//                 }else {
//                     humidiArray[i]=String.valueOf(0);
//                     illumiArray[i]=String.valueOf(0);
//                     temperArray[i] = String.valueOf(0);
//                 }
             }
             FarmDataT data = new FarmDataT(temperArray,humidiArray,illumiArray);
//             data = new ArrayList();
//             data.add(temperArray);
//             data.add(humidiArray);
//             data.add(illumiArray);
             System.out.println("data ==> " + data.toString());
             return ResponseUtils.setSuccess(data);
//             responseUtils.setAnyFarm("temperArray", temperArray);
//             responseUtils.setAnyFarm("humidiArray", humidiArray);
//             responseUtils.setAnyFarm("illumiArray", illumiArray);
         } else {
             responseUtils.setMessage("当前农田还没有数据,请采集数据");
             responseUtils.setSuccess("查询失败");
         }

        return  responseUtils;
   }
//
//    @GetMapping("/getSingleFarmData")
//    @ResponseBody
//    public ResponseUtils getSingleFarmData(String farm_id, String beginDate, String endDate){
//        List<FarmData> list = farmService.getFarmData(farm_id,beginDate,endDate);
//        return ResponseUtils.setSuccess(list);
//    }
//


//    @GetMapping("/getRecentlySingleFarmData")
//    @ResponseBody
//    public ResponseUtils getRecentlySingleFarmData(String farm_id){
//        Date today = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//格式化一下
//        Calendar calendar1 = Calendar.getInstance();//获取对日期操作的类对象
//        calendar1.add(Calendar.DATE, -7);
//        Date startDay = calendar1.getTime();
//        return getSingleFarmData(farm_id,startDay,today);
//    }
//

    @ResponseBody
    @PostMapping("/updateImg")
    ResponseUtils updateFarmImg(@RequestParam("id") int id, @RequestParam("file") MultipartFile uploadFile){

        if(uploadFile.isEmpty())
            return ResponseUtils.setFailure("上传文件失败");

        String url = UploadUtil.basePath + "farmImg/";
        String fileName = UploadUtil.getFileName(uploadFile.getOriginalFilename());

        //上传文件
        File file = new File(url, fileName);
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        try {
            uploadFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("存储文件失败!");
            return ResponseUtils.setFailure("存储文件失败，请联系管理员");
        }


        //更新信息
        String oldUrl = farmService.getFarmById(id).getImgUrl();

        if(!farmService.updateImg(id, url + fileName)){
            return ResponseUtils.setFailure("更新数据出错，请联系管理员");
        }



        //清除旧照片
        if(StringUtils.isNotBlank(oldUrl)){
            new File(oldUrl).delete();
        }

        return ResponseUtils.setSuccess("");
    }
}
